package ac.github.os.internal.core.action.entity

import ac.github.os.internal.core.action.Action
import ac.github.os.internal.core.action.IEntityAction
import ac.github.os.internal.core.config.StringConfig
import ac.github.os.internal.core.config.get
import ac.github.os.internal.session.Cache
import ac.github.os.internal.session.Session
import org.bukkit.Bukkit
import taboolib.common.platform.Awake
import taboolib.common.platform.function.submit

abstract class HealthAction(
    val name: String
) : IEntityAction {

    override val namespace: String
        get() = "entity:health:$name"


}

@Awake
class HealthAddAction : HealthAction("add") {
    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val value = config.get<Double>("val", single = true) ?: return
        if (!Bukkit.isPrimaryThread()) {
            submit(async = false) {
                add(cache, value)
            }
        } else {
            add(cache, value)
        }
    }

    fun add(cache: Cache, value: Double) {
        cache.filterIsEntities().forEach {
            it.health = (it.health + value).coerceAtMost(it.maxHealth)
        }
    }

}

@Awake
class HealthTakeAction : HealthAction("take") {
    override fun onExecute(session: Session, cache: Cache, config: StringConfig) {
        val value = config.get<Double>("val", single = true) ?: return
        if (!Bukkit.isPrimaryThread()) {
            submit(async = false) {
                take(cache, value)
            }
        } else {
            take(cache, value)
        }
    }

    fun take(cache: Cache, value: Double) {

        cache.filterIsEntities().forEach {
            it.health = (it.health - value).coerceAtLeast(0.0)
        }
    }

}